package com.adminx.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.adminx.entity.Account;
import com.adminx.pojo.AccountPojo;
import com.adminx.pojo.MenuPojo;
import com.adminx.util.PageResults;

@Repository
public class AccountDao extends BaseDao<Account, Long>{  
	
	
	protected static Logger LOGGER = Logger.getLogger(AccountDao.class);

	/**
	 * 通过id返回User
	 * @param id
	 * @return
	 */
	public Account getAccount(Long id){
		String hql = "From Account t where t.accountId = ?";
		return this.getByHQL(hql, id);
	}

	/**
	 * 用户是否存在
	 * @param id
	 * @return
	 */
	public boolean  isAccountExists(String userName){
		String hql = "select count(*) FROM Account u where u.userName = ?";
		Long count = this.countByHql(hql, userName);
		return count > 0;
	}

	/**
	 * 通过用户名查找用�?
	 * @param userName
	 * @return
	 */
	public Account findByUserName(String userName){
		String hql = "From Account u where u.userName = ?";
		Account user = this.getByHQL(hql, userName);
		return user;
	}

	/**
	 * 分页查找用户
	 * @param userName
	 * @return
	*/
	public PageResults<AccountPojo> query(Integer pageIndex, Integer pageSize, String searchText){
		
		String sql = 
			"SELECT " +
			"	t.account_id id, " +
			"	t.user_name userName, " +
			"	t.phone phone, " +
			"	DATE_FORMAT( " +
			"		t.last_login_time, " +
			"		'%Y-%m-%d %H:%i:%S' " +
			"	) lastLoginTime, " +
			"	DATE_FORMAT( " +
			"		t.register_time, " +
			"		'%Y-%m-%d %H:%i:%S' " +
			"	) registerTime, " +
			"	t.login_count loginCount " +
			"FROM " +
			"	xx_account t";
				
		String countSql = 
			"SELECT count(1) " +
			"FROM " +
			"	xx_account t";
			
		if(!StringUtils.isBlank(searchText)){
			sql += " WHERE t.user_name like '%" + searchText + "%' or t.remark like '%" + searchText + "%' ";
			countSql += " WHERE t.user_name like '%" + searchText + "%' or t.remark like '%" + searchText + "%' ";
		}	
		
		return this.findPageByFetchedSql(AccountPojo.class, sql, countSql, pageIndex, pageSize);
	}

	/**
	 * 通过用户ID查找权限编码
	 * @param accountID
	 * @return
	 */
	public List<Object>  findAuthorityCodeByAccountID(Long accountID){
		String sql = " SELECT e.authority_code FROM xx_account a,xx_role c,xx_role_authority d,xx_authority e "+
					 " WHERE a.role_id  = c.role_id AND c.role_id = d.role_id AND d.authority_id = e.authority_id "+
					 " AND a.account_id = ?";
		List<Object> codeList = this.getListBySQL2(sql, accountID);
		return codeList;
	}

	/**
	 * 查找权限资源对应关系
	 * @return
	 */
	public List<Object[]> findAuthorityResourceRelation(){
		String sql = " SELECT a.authority_code,r.resource_path "+
					 " FROM xx_authority a,xx_authority_resource ar,xx_resources r "+
					 " WHERE a.authority_id = ar.authority_id AND ar.resource_id = r.resource_id";
		@SuppressWarnings("unchecked")
		List<Object[]> authorityResourceRelations = this.getSession().createSQLQuery(sql).list();
		return authorityResourceRelations;
	}

	/**
	 * 查询菜单
	 * @return
	*/
	public List<MenuPojo> findMenuByAuthority(){
		String sql = " SELECT r.resource_id,r.resource_name,r.resource_path,r.resource_type,r.parent_id,r.resource_icon "+
					 " FROM xx_resources r,xx_authority_resource ar,xx_authority a where "+
					 " r.resource_id = ar.resource_id and a.authority_id = ar.authority_id order by r.resource_order ";
		
		@SuppressWarnings("unchecked")
		List<Object[]> queryList = this.getSession().createSQLQuery(sql).list();
		List<MenuPojo> menus = new ArrayList<>();
		for(int i = 0;i<queryList.size();i++){
			MenuPojo menu = new MenuPojo();
			menu.setId(queryList.get(i)[0] == null?null:Long.parseLong(queryList.get(i)[0].toString()));
			menu.setParentID(queryList.get(i)[4] == null?null:Long.parseLong(queryList.get(i)[4].toString()));
			menu.setResourceName(queryList.get(i)[1] == null?"":queryList.get(i)[1].toString());
			menu.setResourcePath(queryList.get(i)[2] == null?"":queryList.get(i)[2].toString());
			menu.setResourceType(queryList.get(i)[3] == null?null:Integer.parseInt(queryList.get(i)[3].toString()));
			menu.setResourceIcon(queryList.get(i)[5] == null?"":queryList.get(i)[5].toString());
			menus.add(menu);
		}
		return menus;
	}
	
	/**
	 * 查询资源,返回JSON
	 * @return
	 */
	public StringBuilder getJsonMenu(){
		String sql = " SELECT r.resource_id,r.resource_name,r.resource_path,r.resource_type,r.parent_id, "+
					 " r.resource_icon FROM xx_resources r  ORDER BY r.resource_order ";
		@SuppressWarnings("unchecked")
		List<Object[]> queryList = this.getSession().createSQLQuery(sql).list();
		StringBuilder sb = new StringBuilder("[");
		for(int i = 0;i<queryList.size();i++){
			if(i<queryList.size()-1){
				sb.append("{\"id\":\""+queryList.get(i)[0]+"\",\"pId\":\""+queryList.get(i)[4]+"\",\"name\":\""+queryList.get(i)[1]+"\"},");
			}else{
				sb.append("{\"id\":\""+queryList.get(i)[0]+"\",\"pId\":\""+queryList.get(i)[4]+"\",\"name\":\""+queryList.get(i)[1]+"\"}");
			}
		}
		sb.append("]");
		return sb;
	}
	
	/**
	 * 通过ID删除账号
	 * @param accountId
	 */
	public int delBatch(String ids) {
		String[] idsArray = ids.split(",");
		String hql = "";
		for (int i = 0; i < idsArray.length; i++) {
			if (i == 0) {
				hql = "accountId=" + idsArray[i];
			} else {
				hql = hql + " or accountId=" + idsArray[i];
			}
		}
		int updateCount = this.getSession().createQuery("DELETE FROM Account WHERE " + hql).executeUpdate();
		return updateCount;
	}
	
	/**
	 * 给账号赋予角色
	 */
	public void grantRole(Long accountID,Long roleID){
		String sql = "update xx_account t set t.role_id = "+roleID+" where t.account_id = "+accountID;
		this.getSession().createSQLQuery(sql).executeUpdate();
	};
}
